/**
 * Apr 1, 2010
 */
package org.tomale.id.documents.management;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.preference.IPreferenceStore;
import org.tomale.id.ProviderException;
import org.tomale.id.common.KeyValuePair;

/**
 * @author ferd
 *
 */
public class DocumentManager {
	
	public final static String EXT_ID = "org.tomale.id.document.store";

	public static List<KeyValuePair<String, String>> getStores(){
		ArrayList<KeyValuePair<String, String>> stores = new ArrayList<KeyValuePair<String,String>>();
		IConfigurationElement[] elems = Platform.getExtensionRegistry().getConfigurationElementsFor("org.tomale.id.document.store");
		for(IConfigurationElement elem : elems){
			stores.add(new KeyValuePair<String, String>(elem.getAttribute("class"), 
					elem.getAttribute("description")));
		}
		return stores;
	}
	
	public static IDocumentStore getStore() throws ProviderException {
		IPreferenceStore store = Activator.getDefault().getPreferenceStore();
		String id = store.getString(PreferenceConstants.DOCUMENT_STORE_ID);
		IConfigurationElement[] elems = Platform.getExtensionRegistry().getConfigurationElementsFor(EXT_ID);
		for(IConfigurationElement elem : elems){
			if(id.equals(elem.getAttribute("class"))){
				try {
					Activator.log(Status.INFO, MessageFormat.format("Creating instance of {0} document store.", id));
					Object o = elem.createExecutableExtension("class");
					if(o instanceof IDocumentStore){
						return (IDocumentStore) o;
					}
				}catch(CoreException e){
					throw new ProviderException(MessageFormat.format("Unable to create document store {0}.", id));
				}
			}
		}
		return null;
	}
}
